﻿/*
 * @Autor: PK
 * @Date: 2021/12/30 10:18:SS
 */

using System;
using System.Collections.Generic;
using GMap.NET;
using Itinero;
using Itinero.LocalGeo;
using Itinero.Profiles;
using Vehicle = Itinero.Osm.Vehicles.Vehicle;

namespace ShkSimulation.desktop.component.tools {

	public class OpenStreetMapRoutingProvider: RoutingProvider {
		
		private Router osmRouter;
		private IProfileInstance profileInstance;
		
		public OpenStreetMapRoutingProvider(Router router, IProfileInstance profileInstance = null) {
			this.profileInstance = profileInstance?? Vehicle.Car.Fastest();
			this.osmRouter = router;
		}

		public bool IsConnected(PointLatLng pointLatLng) {
			Result<RouterPoint> routerPoint = 
				osmRouter.TryResolveConnected(profileInstance, new Coordinate((float)pointLatLng.Lat, (float)pointLatLng.Lng));
			if (routerPoint.IsError) {
				return false;
			}
			return true;
		}

		public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom) {
			Result<Route> calculate = osmRouter.TryCalculate(profileInstance, new Coordinate((float) start.Lat, (float) start.Lng), new Coordinate((float) end.Lat, (float) end.Lng));
			if (calculate.IsError) {
				return null;
			}
			List<PointLatLng> pointLatLngs = ResultRouteToPoints(calculate.Value);
			string name = $"{start.Lat},{start.Lng}:{end.Lat},{end.Lng}";
			MapRoute result = new MapRoute(pointLatLngs, name);
			result.Tag = calculate.Value;
			return result;
		}
		
		
		public List<PointLatLng> ResultRouteToPoints(Route route) {
			Coordinate[] routeShape = route.Shape;
			List<PointLatLng> pointLatLngs = new List<PointLatLng>();
			foreach (var coordinate in routeShape) {
				pointLatLngs.Add(new PointLatLng(coordinate.Latitude, coordinate.Longitude));
			}
			return pointLatLngs;
		}

		public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom) {
			throw new NotImplementedException();
		}

	}

}